/*
  弹窗组件
*/
import './modal.css';

export default class Modal {
  constructor(content = '', title = '') {
    this.modal = document.createElement('div');
    this.modal.className = 'modal-mask';

    // 弹窗
    const contentDiv = document.createElement('div');
    contentDiv.className = 'modal-content';

    // 标题
    if (title) {
      const titleDiv = document.createElement('div');
      titleDiv.className = 'modal-title';
      titleDiv.innerHTML = title;
      contentDiv.appendChild(titleDiv);
    }

    // 主体
    const bodyDiv = document.createElement('div');
    bodyDiv.className = 'modal-body';
    bodyDiv.innerHTML = content;

    // close btn
    const closeBtn = document.createElement('div');
    closeBtn.className = 'modal-close';
    bodyDiv.appendChild(closeBtn);

    // body into content
    contentDiv.appendChild(bodyDiv);

    // content into modal
    this.modal.appendChild(contentDiv);

    // bind event
    this.modal.addEventListener('click', (e) => {
      if (e.target === this.modal || e.target === closeBtn) {
        this.hide();
      }
    });
  }

  show() {
    document.body.appendChild(this.modal);
    requestAnimationFrame(() => {
      this.modal.classList.add('modal-visible');
    });
  }

  hide() {
    this.modal.classList.remove('modal-visible');
    this.modal.addEventListener('transitionend', () => {
      if (this.modal.parentNode) {
        this.modal.parentNode.removeChild(this.modal);
      }
    }, { once: true });
  }
}
